import {set as setConfig} from '$ui/config'
import {getTokenFromCache, removeUserToCache, removeTokenFromCache} from '@/helper/utils'
import {whitList} from '@/constant'
import {dynamicRouter} from '@/helper/dynamicMenu'


// 写入运行时配置
setConfig({
  /**
   * 路由模式
   */
  router: {
    mode: 'hash',
    base: '/'
  },

  /**
   * 是否应用自动生成的路由配置
   */
  autoRoutes: true,

  /**
   * 权限控制配置
   */
  access: {
    // 启用请求权限控制
    axios: true,

    // 启用路由权限控制
    router: true,

    // 缓存存储方式 session 或 local
    storage: 'session',

    // 登录页面路径
    loginPath: '/login',

    // 权限不足页面路径
    authorizePath: '/403',
    request: (access, options, config) => {
      if (config.url.indexOf('/sys/login') < 0) {
        //  config.headers[options.authorization] = '' + getTokenFromCache()
        config.headers.token = getTokenFromCache()
      }
      return config
    },

    response: function (vm, options, res) {
      // 登录过期跳转到登录页
      if (res && res.data) {
        if (res.data.code === 401) {
          removeUserToCache()
          removeTokenFromCache()
          this.logout()
          // 退出登录
        } else if (res.data.code !== 0) {
          vm.$notify.warning(res.data.msg)
        }
      }
      return res
    },
    beforeEach(to, from, next) {
      return new Promise((resolve, reject) => {
        const $router = this.options.$router
        const token = getTokenFromCache()
        if(token || whitList.includes(to.path)) {
          if(token && !$router.options.isAddDynamicMenuRoutes) {
            dynamicRouter($router).then(_ => {
              next(to)
            })
          } else {
            next()
          }
        } else {
          this.logout()
        }
      })
    }
  },

  /**
   * 开启访问分析追踪
   */
  analysis: true
})


